package com.hangzhou.xyj.ui.adapter;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;

import com.hangzhou.xyj.R;
import com.hangzhou.xyj.db.preferences.CommonPreferences;
import com.hangzhou.xyj.manager.IntentManager;
import com.hangzhou.xyj.model.CommentModel;
import com.hangzhou.xyj.model.DynamicDetailModel;
import com.hangzhou.xyj.model.GroupModel;
import com.hangzhou.xyj.model.type.EIntentTagType;
import com.hangzhou.xyj.net.handler.DeleteCommentHandler;
import com.hangzhou.xyj.net.handler.GetGroupDetailHandler;
import com.hangzhou.xyj.net.http.HttpLoader;
import com.hangzhou.xyj.net.listener.HttpResponseListener;
import com.hangzhou.xyj.net.request.DeleteCommentReq;
import com.hangzhou.xyj.net.request.GetGroupDetailReq;
import com.hangzhou.xyj.ui.activity.ExpertInfoActivity;
import com.hangzhou.xyj.ui.activity.GroupDetailActivity;
import com.hangzhou.xyj.ui.activity.HomePageActivity;
import com.hangzhou.xyj.ui.adapter.viewholder.CommentViewHolder;
import com.hangzhou.xyj.ui.dialog.LoadingDialog;
import com.hangzhou.xyj.ui.widget.CircleImageView;
import com.hangzhou.xyj.ui.widget.SelectMenuDialog;
import com.hangzhou.xyj.ui.widget.views.MyTextView;
import com.hangzhou.xyj.utils.PublicUtil;
import com.hangzhou.xyj.utils.StringUtil;
import com.hangzhou.xyj.utils.ToastUtil;
import com.hangzhou.xyj.utils.constants.DataKey;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by yaohuix on 2016/3/21  15:30
 * <p/>
 * 说明：动态明细Adapter
 */
public class DynamicDetailAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    OnNumChangeListener mListener;
    private Context mContext;
    private LayoutInflater mInflater;
    private DynamicDetailModel mDatas = new DynamicDetailModel();//动态详情数据
    private List<CommentModel> mCommentList;//评论列表
    private int mIntentTag;
    private LoadingDialog mLoadingDialog;
    private String mGroupId;//群id
    private String mEMGroupId;//环信id

    private ImgGridAdapter mAdapter;

    public DynamicDetailAdapter(Context context) {
        mContext = context;
        mInflater = LayoutInflater.from(context);
        mLoadingDialog = new LoadingDialog(context);
    }

    public void setIntentTag(int tag) {
        this.mIntentTag = tag;
    }

    /**
     * 更新评论列表
     *
     * @param
     * @return
     * @author yaohuix
     * @date 2016/3/22 10:29
     */
    public void updateCommentList(List<CommentModel> list) {
        if (list == null) {
            list = new ArrayList<>();
        }
        mCommentList = list;
        notifyDataSetChanged();
    }

    /**
     * 更新评论详情
     *
     * @param
     * @return
     * @author yaohuix
     * @date 2016/3/22 10:31
     */
    public void updateBaseCommentInfo(DynamicDetailModel data) {
        if (data == null) {
            data = new DynamicDetailModel();
        }
        mDatas = data;
        notifyDataSetChanged();
    }

    public void setOnNumChangeListener(OnNumChangeListener listener) {
        this.mListener = listener;
    }

    @Override
    public int getItemCount() {
        if (mCommentList == null || mCommentList.size() == 0) {
            return 1;
        }
        return mCommentList.size() + 1;
    }

    @Override
    public int getItemViewType(int position) {
        return position;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        switch (viewType) {
            case 0:
                return new BaseInfoViewHolder(mInflater.inflate(R.layout.layout_item_dynamic_info, viewGroup, false));
            case 1:
            default:
                return new CommentViewHolder(mInflater.inflate(R.layout.layout_drama_play_comment, viewGroup, false));
        }
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder viewHolder, final int position) {
        if (viewHolder == null) return;
        switch (position) {
            case 0:

                ((BaseInfoViewHolder) viewHolder).setData(mDatas);
                ((BaseInfoViewHolder) viewHolder).mCivHeadImg.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent;
                        switch (PublicUtil.getUserType(mDatas.getType(), mDatas.getCheckFlag())) {
                            case FAMOUS_EXPERT:
                                intent = new Intent(mContext, ExpertInfoActivity.class);
                                intent.putExtra(DataKey.INTENT_TAG, EIntentTagType.TAG_STAGE_EXPERT.getValue());
                                break;
                            case FAMOUS_TEAM:
                                intent = new Intent(mContext, ExpertInfoActivity.class);
                                intent.putExtra(DataKey.INTENT_TAG, EIntentTagType.TAG_STAGE_TEAM.getValue());
                                break;
                            default:
                                intent = new Intent(mContext, HomePageActivity.class);
                                break;
                        }
                        intent.putExtra(DataKey.INDEX, Integer.valueOf(mDatas.getUserId()));
                        intent.putExtra(DataKey.TITLE, mDatas.getNickname());
                        IntentManager.getInstance().goActivity(mContext, intent);
                    }
                });
                break;
            case 1:
            default:
                final CommentModel model = mCommentList.get(position - 1);
                ((CommentViewHolder) viewHolder).setData(model);
                //我的评论 添加删除功能
                //如果是我自己的评论
                if (model.getUserId().equals(String.valueOf(CommonPreferences.getUserId(mContext)))) {
                    viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            SelectMenuDialog menuDialog = new SelectMenuDialog(mContext);
                            String[] menu = new String[]{"删除"};
                            menuDialog.setMenu(menu, new SelectMenuDialog.SelectMenuClickListener() {
                                @Override
                                public void onSelectMenuClick(Dialog dialog, View item, int innerPosition) {
                                    dialog.dismiss();
                                    deleteComment(mCommentList.get(position - 1).getId(), position - 1, viewHolder.getAdapterPosition());
                                }
                            });
                            menuDialog.show();
                        }
                    });
                } else {
                    ((CommentViewHolder) viewHolder).mCivHeadImg.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {//跳转个人信息主页
                            IntentManager.getInstance().goExpertInfoActivity(mContext, Integer.valueOf(model.getUserId()),
                                    model.getUserName(), PublicUtil.getUserType(model.getType(), model.getCheckFlag()));
                        }
                    });
                }
        }
    }

    /**
     * 删除评论
     *
     * @param
     * @return
     * @author yaohuix
     * @date 2016/4/7 17:01
     */
    public void deleteComment(int commentId, final int position, final int adapterPosition) {
        DeleteCommentReq commentReq = new DeleteCommentReq(commentId);
        HttpLoader.getInstance().sendRequest(new DeleteCommentHandler(commentReq, new HttpResponseListener() {
            @Override
            public void onStart() {
                mLoadingDialog.show();
            }

            @Override
            public void onSuccess(Object model) {
                mLoadingDialog.dismiss();
                //删除成功
                mCommentList.remove(adapterPosition - 1);
                notifyItemRemoved(adapterPosition);
                //刷新评论数
                mListener.onDeleteChange(OnNumChangeListener.COMMENT_TYPE);
            }

            @Override
            public void onFail(String msg) {
                mLoadingDialog.dismiss();
            }

            @Override
            public void onDone(String msg) {
                mLoadingDialog.dismiss();
            }

            @Override
            public void onError() {
                mLoadingDialog.dismiss();
            }
        }, 0));
    }

    public void getGroupInfo() {
        GetGroupDetailReq getGroupDetailReq = new GetGroupDetailReq(mGroupId);
        HttpLoader.getInstance().sendRequest(new GetGroupDetailHandler(getGroupDetailReq, new HttpResponseListener() {
            @Override
            public void onStart() {

            }

            @Override
            public void onSuccess(Object model) {
                GroupModel groupModel = (GroupModel) model;
                mEMGroupId = groupModel.getGroupCode();
            }

            @Override
            public void onFail(String msg) {

            }

            @Override
            public void onDone(String msg) {

            }

            @Override
            public void onError() {

            }
        }, 0));
    }

    /**
     * 删除评论 取消点赞的时候 刷新动态详情下面的数字，回调接口
     *
     * @param
     * @author yaohuix
     * @return
     * @date 2016/4/8 17:42
     */
    public interface OnNumChangeListener {
        int LIKE_TYPE = 0;
        int COMMENT_TYPE = 1;

        void onAddChange(int type);

        void onDeleteChange(int type);
    }

    /**
     * 基本信息
     *
     * @param
     * @author yaohuix
     * @return
     * @date 2016/3/21 15:42
     */
    class BaseInfoViewHolder extends RecyclerView.ViewHolder {
        private CircleImageView mCivHeadImg;//头像
        private MyTextView mTvName;//名字
        private MyTextView mTvTime;//时间
        private MyTextView mTvLocation;//地点
        private MyTextView mTvContent;//评论内容
        private GridView mGvImgList;//图片列表
        private MyTextView mTvTransferNum;//转发数
        private MyTextView mTvLikeNum;//点赞数
        private MyTextView mTvCommentNum;//评论数

        private DynamicDetailModel mData;
        private MyTextView mTvNobody;//抢沙发
        private View mVNobody;//下面的黑色间隔条

        public BaseInfoViewHolder(View itemView) {
            super(itemView);
            mCivHeadImg = (CircleImageView) itemView.findViewById(R.id.civ_header);
            mTvName = (MyTextView) itemView.findViewById(R.id.mtv_name);
            mTvTime = (MyTextView) itemView.findViewById(R.id.mtv_time);
            mTvLocation = (MyTextView) itemView.findViewById(R.id.mtv_location);
            mTvContent = (MyTextView) itemView.findViewById(R.id.mtv_content);
            mGvImgList = (GridView) itemView.findViewById(R.id.image_grid);
            mTvTransferNum = (MyTextView) itemView.findViewById(R.id.mtv_transfer_num);
            mTvLikeNum = (MyTextView) itemView.findViewById(R.id.mtv_like_num);
            mTvCommentNum = (MyTextView) itemView.findViewById(R.id.mtv_comment_num);
            mTvNobody = (MyTextView) itemView.findViewById(R.id.mtv_nobody);
            mVNobody = itemView.findViewById(R.id.v_nobody);
            mGvImgList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    IntentManager.getInstance().goPhotoViewActivity(mContext, mData.getImageList(), position);
                }
            });

            mAdapter = new ImgGridAdapter(mContext, null);
            mGvImgList.setAdapter(mAdapter);
        }

        public void setData(final DynamicDetailModel data) {
            this.mData = data;
            mCivHeadImg.displayImage(data.getUserHead());
            mTvName.setText(data.getNickname());
            mTvName.setCompoundDrawablesWithIntrinsicBounds(null, null, PublicUtil.getAuthenIconDrawable(mContext,
                    PublicUtil.getUserType(data.getType(), data.getCheckFlag())), null);
            mTvTime.setText(data.getTime());
            mTvLocation.setText(data.getLocation());
            //设置文本颜色
            final String content = data.getContent();
            if (StringUtil.isNotEmpty(content)) {
                String[] strArray = PublicUtil.getGroupInvite(content);
                if (strArray != null) {
                    String other = strArray[0];
                    mGroupId = strArray[1];
                    //获取圈子详情
                    getGroupInfo();
                    SpannableString spannableStr = new SpannableString(other + mGroupId);
                    spannableStr.setSpan(new NoLineClickSpan() {
                        @Override
                        public void onClick(View widget) {
                            if (StringUtil.isNotEmpty(mEMGroupId)) {
                                Intent intent = new Intent(mContext, GroupDetailActivity.class);
                                intent.putExtra(DataKey.GROUP_CODE, mEMGroupId);
                                IntentManager.getInstance().goActivity(mContext, intent);
                            } else {
                                ToastUtil.show("该圈子不存在或已被删除！");
                            }
                        }
                    }, other.length(), other.length() + mGroupId.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                    mTvContent.setText(spannableStr);
                    mTvContent.setMovementMethod(LinkMovementMethod.getInstance());
                } else {
                    mTvContent.setText(data.getContent());
                }
            }
            mAdapter.update(mDatas.getImageList());
            mTvTransferNum.setText(String.valueOf(data.getTransferNum()));
            mTvLikeNum.setText(String.valueOf(data.getLikeNum()));
            mTvCommentNum.setText(String.valueOf(data.getCommentNum()));
            if (mCommentList == null || mCommentList.size() == 0) {
                mTvNobody.setVisibility(View.VISIBLE);
                mVNobody.setVisibility(View.VISIBLE);
            } else {
                mTvNobody.setVisibility(View.GONE);
                mVNobody.setVisibility(View.GONE);
            }
        }

        /**
         * 设置转发数，评论数，点赞数等数字信息
         *
         * @param
         * @return
         * @author yaohuix
         * @date 2016/4/1 13:54
         */
        public void setNumData(DynamicDetailModel data) {
            mTvTransferNum.setText(String.valueOf(data.getTransferNum()));
            mTvLikeNum.setText(String.valueOf(data.getLikeNum()));
            mTvCommentNum.setText(String.valueOf(data.getCommentNum()));
            if (data.getCommentNum() == 0) {
                mTvNobody.setVisibility(View.VISIBLE);
                mVNobody.setVisibility(View.VISIBLE);
            } else {
                mTvNobody.setVisibility(View.GONE);
                mVNobody.setVisibility(View.GONE);
            }
        }
    }

    /**
     * 没有下划线的点击
     */
    private abstract class NoLineClickSpan extends ClickableSpan {
        @Override
        public void updateDrawState(TextPaint ds) {
            ds.setColor(ds.linkColor);
            ds.setUnderlineText(false); //去掉下划线
        }
    }
}
